package com.newtest.demos.Controller;


import com.newtest.demos.Service.LoginService;
import com.newtest.demos.pojo.LoginUser;
import com.newtest.demos.pojo.Result;
import com.newtest.demos.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
public class LoginController {


    @Autowired
    private LoginService loginService;

    //登录
    @PostMapping("/login")
    public Result login(@RequestBody LoginUser loginUser){
//        log.info("接收到的登录请求：\nUsername: {}\nPassword: {}", loginUser.getUsername(), loginUser.getPassword());
//        log.info("LoginUser对象: {}", loginUser); // 打印LoginUser对象
        log.info("用户登录：{}",loginUser);
        LoginUser User = loginService.login(loginUser);

//        登录成功，需要生成令牌,并下发
        if (User != null){
            Map<String,Object> claims = new HashMap<>();

            claims.put("username",User.getUsername());

            String jwt = JwtUtils.generateJwt(claims);//jwt中包含当前登录的用户名的信息
            return Result.success(jwt);
        }

        //登录失败，需要返回信息

        return Result.error(0,"用户名或密码错误");
    }
    //注册
    @PostMapping("/register")
    public Result registerUser(@RequestBody LoginUser loginUser) {
        //用户注册，需要用户名，密码，邮箱
        log.info("注册:{}{}{}",loginUser.getUsername(),loginUser.getPassword(),loginUser.getEmail());

//        try {
//            loginService.registerUser(loginUser);
//            return("User registered successfully!");
//        } catch (DataIntegrityViolationException ex){
//            return ("Username already exists!");
//        }
        // 检查用户名是否已存在
        boolean isUsernameExist = loginService.isUsernameExists(loginUser.getUsername());
        if (isUsernameExist) {
            return Result.error(201,"用户名已存在");
        }

        // 检查邮箱是否已存在
        boolean isEmailExist = loginService.isEmailExists(loginUser.getEmail());
        if (isEmailExist) {
            return Result.error(202,"邮箱已存在");
        }

        loginService.registerUser(loginUser);
        return Result.success();
    }

    //用户修改密码
    @PostMapping("/userupdate")
    public Result updateUser(@RequestBody LoginUser loginUser,HttpServletRequest request){

        // 从请求头中获取JWT令牌并解析
        String username = loginService.username(request);

        // 确保请求体中的username与解析出的username一致
        if (!loginUser.getUsername().equals(username)) {
//            throw new AccessDeniedException("Access denied for user: " + username);
//            return Result.error("用户名不一致");
            return Result.error(0,"用户名不一致");
        }
        loginService.updateUser(loginUser);

        return Result.success("修改成功");
    }

    //用户注销
    @DeleteMapping("/userdelete")
    public Result deleteLoginUser(@RequestBody LoginUser loginUser,HttpServletRequest request) {
        // 从请求头中获取JWT令牌并解析
        String username = loginService.username(request);

        // 确保请求体中的username与解析出的username一致
        if (!loginUser.getUsername().equals(username)) {
//            throw new AccessDeniedException("Access denied for user: " + username);
//            return Result.error("用户名不一致");
            return Result.error(0,"用户名不一致");
        }
        loginService.deleteUser(loginUser);
        return Result.success("已删除");
    }
    //查询个人资料
    @GetMapping("/userme")
    public List<LoginUser> findAllInventory(HttpServletRequest request) {

        String username = loginService.username(request);
        return loginService.findAllUser(username);
    }
    //上传图片（头像）
    @PostMapping("/user/image")
    public Result image(MultipartFile image) throws IOException {
         //获取原始文件名
        String originalFilename = image.getOriginalFilename();
        //构建新文件名
        String newFileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        image.transferTo(new File("D:/image/"+newFileName));
        return Result.success("D:/image/"+newFileName);
    }

    //文件下载
    @GetMapping("/user/download")
    public void download(String name, HttpServletResponse response){

        try {
            //输入流，读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File("D:/image/"+name));
            //输出流，将文件写回浏览器，展示图片
            ServletOutputStream outputStream = response.getOutputStream();

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }



    }
}
